{
 "metadata": {
  "name": "",
  "signature": "sha256:5c6e8e84c4cc19ad05411422b2be10c4fb8f826c52c8e8ef6a62665b19c5f0af"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>"
     ]
    },
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Financial Time Series Visualization &mdash; Basics"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "**PyData London 2015**"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Yves Hilpisch\n",
      "\n",
      "<a href='mailto:team@tpq.io'>team@tpq.io</a> | <a href='http://tpq.io'>http://tpq.io</a>\n",
      "\n",
      "The Python Quants GmbH"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import warnings\n",
      "warnings.simplefilter('ignore')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Example Data Retrieval"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Retrieval and visualization of financial data."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import pandas.io.data as web"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL = web.DataReader('AAPL', data_source='yahoo')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL.info()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL.tail()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Basic matplotlib plotting"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%matplotlib inline"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL['Adj Close'].plot()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import numpy as np\n",
      "log_rets = np.log(AAPL['Adj Close'] / AAPL['Adj Close'].shift(1))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "log_rets.hist(bins=30)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import matplotlib.pyplot as plt"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "log_rets.hist(figsize=(10, 6), bins=30)\n",
      "plt.xlabel('log returns')\n",
      "plt.ylabel('frequency')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Financial Plots"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import matplotlib.finance as mpf"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "start = (2015, 4, 1)\n",
      "end = (2015, 5, 30)\n",
      "quotes = mpf.quotes_historical_yahoo_ochl('^GDAXI', start, end)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "quotes[:2]"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "fig, ax = plt.subplots(figsize=(10, 6))\n",
      "fig.subplots_adjust(bottom=0.2)\n",
      "mpf.candlestick_ochl(ax, quotes, width=0.6, colorup='b', colordown='r')\n",
      "plt.grid(True)\n",
      "ax.xaxis_date()\n",
      "# dates on the x-axis\n",
      "ax.autoscale_view()\n",
      "plt.setp(plt.gca().get_xticklabels(), rotation=30)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "fig, ax = plt.subplots(figsize=(8, 5))\n",
      "mpf.plot_day_summary(ax, quotes, colorup='b', colordown='r')\n",
      "plt.grid(True)\n",
      "ax.xaxis_date()\n",
      "plt.title('DAX Index')\n",
      "plt.ylabel('index level')\n",
      "plt.setp(plt.gca().get_xticklabels(), rotation=30)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "ggplot Style Plotting"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "plt.style.use('ggplot')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL['Adj Close'].plot()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "log_rets.hist(figsize=(10, 6), bins=30)\n",
      "plt.xlabel('log returns')\n",
      "plt.ylabel('frequency')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": [
      "seaborn for Statistical Plotting"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import seaborn as sns\n",
      "sns.set()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL['Adj Close'].plot()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "fig, ax = plt.subplots(figsize=(10, 6))\n",
      "fig.subplots_adjust(bottom=0.2)\n",
      "mpf.candlestick_ochl(ax, quotes, width=0.6, colorup='b', colordown='r')\n",
      "plt.grid(True)\n",
      "ax.xaxis_date()\n",
      "# dates on the x-axis\n",
      "ax.autoscale_view()\n",
      "plt.setp(plt.gca().get_xticklabels(), rotation=30)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import pandas as pd\n",
      "AAPL['42d'] = pd.rolling_mean(AAPL['Adj Close'], 42)\n",
      "AAPL['252d'] = pd.rolling_mean(AAPL['Adj Close'], 200)\n",
      "  # 42 & 252 days trends (moving averages)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL[['Adj Close', '42d', '252d']].plot(figsize=(12, 6))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "MSFT = web.DataReader('MSFT', data_source='yahoo')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "data = pd.DataFrame({'AAPL': AAPL['Adj Close'], 'MSFT': MSFT['Adj Close']})\n",
      "data.tail() "
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import numpy as np\n",
      "rets = np.log(data / data.shift(1))\n",
      "rets.tail()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "sns.jointplot(rets['AAPL'], rets['MSFT'], size=8)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "sns.jointplot(rets['AAPL'], rets['MSFT'], size=8, kind='reg')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": [
      "Interactive Plotting with plotly"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import plotly.plotly as py\n",
      "import cufflinks\n",
      "py.sign_in('Python-Demo-Account', 'gwt101uhh0')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL[['Adj Close', '42d', '252d']].iplot(filename='plotly',\n",
      "                                         world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "AAPL['Adj Close'].iplot(filename='AAPL_fit', bestfit=True, colors=['pink'],\n",
      "                bestfit_colors=['blue'], world_readable=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Interacting & Plotting with R & ggplot"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%load_ext rpy2.ipython"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "aapl = AAPL['Adj Close'].values"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%Rpush aapl"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%R plot(aapl, pch=20, col='blue'); grid(); title(\"Apple Stock Prices\")"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%R x = seq(1, length(aapl), by=1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%R c = coef(lm(aapl ~ x))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%R\n",
      "plot(aapl, pch=19, col='blue')\n",
      "grid(); abline(c, col='red', lwd=5)\n",
      "title('Stock Prices with Regression Line')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%R m = mean(aapl)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%Rpull m"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(\"Average stock price is %5.2f\" % m[0])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>\n",
      "\n",
      "<a href=\"http://tpq.io\" target=\"_blank\">http://tpq.io</a> | <a href=\"http://twitter.com/dyjh\" target=\"_blank\">@dyjh</a> | <a href=\"mailto:team@pqp.io\">team@tpq.io</a>\n",
      "\n",
      "**Quant Platform** |\n",
      "<a href=\"http://quant-platform.com\">http://quant-platform.com</a>\n",
      "\n",
      "**datapark.io** |\n",
      "<a href=\"http://datapark.io\">http://datapark.io</a>\n",
      "\n",
      "**Python for Finance** |\n",
      "<a href=\"http://python-for-finance.com\" target=\"_blank\">Python for Finance @ O'Reilly</a>\n",
      "\n",
      "**Derivatives Analytics with Python** |\n",
      "<a href=\"http://derivatives-analytics-with-python.com\" target=\"_blank\">Derivatives Analytics @ Wiley Finance</a>"
     ]
    }
   ],
   "metadata": {}
  }
 ]
}